#include "Sound.h"
#include "Constants.h"
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <iostream>
using namespace std;


Sound::Sound()
{
	/* Initialization */
	if(SDL_InitSubSystem(SDL_INIT_AUDIO) == -1)
	{
	    throw "SDL Audio subsystem could not be started";
	}
	
	int audio_rate = 22050;
	Uint16 audio_format = AUDIO_S16SYS;
	int audio_channels = 4;
	int audio_buffers = 2048;//4096;
	
	/* Initialization 
	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) == -1)
	{
	    throw "SDL_Mixer could not be started";
	}
	
	impactSound = Mix_LoadWAV("data/sound/thump.wav");
	if(!impactSound)
	{
	    throw "Could not load file from disk";
	}
*/

}

Sound::~Sound()
{

/* Uninitialization 
Mix_FreeChunk(impactSound);
Mix_CloseAudio();
SDL_QuitSubSystem(SDL_INIT_AUDIO);	
*/
}

//Volume is 1 to 128, -1 will use previous volume
void Sound::playImpactSound(float force)
{
	float volume = force/0.0002 * 255;
	if(volume > 255)
	{
		volume = 255;
	}
	int channelMaxVolumes [4] = {63, 126, 189, 255};
	for(int i=0; i<4; i++)
	{
		if (volume < channelMaxVolumes[i])
		{
			playSound(impactSound, i, (int)volume);
			break;
		} 
	}
}

void Sound::playSound(Mix_Chunk * sound, int channel, int volume)
{
	/*int channelNumber = Mix_PlayChannel(channel, sound, 0);
	//cout << "playing sound for force: " << force << " at volume: " << volume << " channel " << channelNumber << "\n";
	if(channelNumber >=0)
	{
		Mix_Volume(channelNumber, (int)volume);
	}*/	
}
